<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\OperationLog;

class AuthController extends Controller
{
    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $credentials = $request->only('username', 'password');
        $remember = $request->has('remember');

        if (!$token = Auth::attempt($credentials, $remember)) {
            // 登录失败时记录日志，使用请求中的用户名
            OperationLog::log(null, 'login_failed', null, null, '用户 ' . $request->username . ' 登录失败');
            return response()->json(['error' => '用户名或密码错误'], 401);
        }

        // 登录成功后记录日志
        OperationLog::log(Auth::id(), 'login', null, null, '用户登录成功');
        return $this->respondWithToken($token);
    }

    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'username' => 'required|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create([
            'username' => $request->username,
            'password' => bcrypt($request->password),
            'status' => 1,
        ]);

        OperationLog::log($user->id, 'register', null, null, '用户注册成功');
        return response()->json(['message' => '注册成功'], 201);
    }

    /**
     * 获取当前登录用户信息
     */
    public function me()
    {
        return response()->json(Auth::user());
    }

    /**
     * 用户登出
     */
    public function logout()
    {
        OperationLog::log(Auth::id(), 'logout', null, null, '用户登出');
        Auth::logout();
        return response()->json(['message' => '登出成功']);
    }

    /**
     * 刷新 token
     */
    public function refresh()
    {
        return $this->respondWithToken(Auth::refresh());
    }

    /**
     * 返回 token 信息
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => Auth::factory()->getTTL() * 60
        ]);
    }
} 